import app from "./app";
import http from "http";
import { AddressInfo } from "net";
import { getConfig } from "./config";
const config = getConfig();
const port = normalizePort(config.port);
const server = http.createServer(app.callback());
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);

function normalizePort(val: string | Number): string | Number | Boolean {
  const port = parseInt(val as string, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

function onError(error: NodeJS.ErrnoException): void {
  if (error.syscall !== "listen") {
    throw error;
  }

  const bind = typeof port === "string" ? "Pipe " + port : "Port " + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
    default:
      throw error;
  }
}

function onListening(): void {
  const addr = server.address();
  const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
  console.log("Server running on " + bind);
  if (typeof addr !== "string") {
    console.log(
      "Try visit http://localhost:" +
        (addr as AddressInfo).port +
        " through yout browser"
    );
  }
}
